using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace proj01
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private int score;

        private bool SplashScreen = true;
        private bool EndScreen = false;
        private Texture2D backgroundTexture;

        private Camera camera;
        private BatField batField;
        private Terrain terrain;
        private Frog frog;   
        private KeyboardState lastKeyboardState;
        private SpriteFont splashfont;

        /// <summary>
        /// A reference to the audio engine we use
        /// </summary>
        AudioEngine audioEngine;

        /// <summary>
        /// The loaded audio wave bank
        /// </summary>
        WaveBank waveBank;

        /// <summary>
        /// The loaded audio sound bank
        /// </summary>
        SoundBank soundBank;

        public BatField BatField{ get { return batField; } }
        public Terrain Terrain { get { return terrain; } }
        public Camera Camera { get { return camera; } }
        public SoundBank SoundBank { get { return soundBank; } }
        public bool endScreen { get { return EndScreen; } set { EndScreen = value; } }
        public int Score { get { return score; } set { score = value; } }

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            batField = new BatField(this);
            terrain = new Terrain(this);
            frog = new Frog(this);
            camera = new Camera(graphics);
            camera.UseChaseCamera = true;
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;
            graphics.ApplyChanges();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            camera.Initialize();
            terrain.Initilize();
            camera.Eye = new Vector3(5000, 5000, 5000);
            batField.BatCreate();
            score = 0;
            //lastKeyboardState = Keyboard.GetState();
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            batField.LoadContent(Content);
            terrain.LoadContent(Content);
            frog.LoadContent(Content);

            splashfont = Content.Load<SpriteFont>("splashscreen");
            backgroundTexture = Content.Load<Texture2D>("frog");

            audioEngine = new AudioEngine("Content\\FrogAudio.xgs");
            waveBank = new WaveBank(audioEngine, "Content\\Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, "Content\\Sound Bank.xsb");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState keyboardState = Keyboard.GetState();

            if(SplashScreen)
            {
                // If the user hits the appropriate key start the game
                if (keyboardState.IsKeyDown(Keys.P))
                {
                    SplashScreen = false;
                }
            }
            else if (!SplashScreen && !EndScreen)
            {
                // Allows the game to exit
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                    this.Exit();
                camera.Update(gameTime);

                Matrix orientation = frog.Transform;

                // Get the frog to jump
                if (keyboardState.IsKeyDown(Keys.Space) && lastKeyboardState.IsKeyUp(Keys.Space))
                {
                    frog.Velocity = 3000 * orientation.Backward + new Vector3(0, 3000, 0);
                    frog.Jump = true;
                }

                // Get the frog to turn
                if (keyboardState.IsKeyDown(Keys.Right))
                {
                    frog.TurnRate = -1;
                }
                else if (keyboardState.IsKeyDown(Keys.Left))
                {
                    frog.TurnRate = 1;
                }
                else
                {
                    frog.TurnRate = 0;
                }

                // Get the frog to turn his head
                if (keyboardState.IsKeyDown(Keys.A))
                {
                    frog.HeadTurnRate = 1;
                }
                else if (keyboardState.IsKeyDown(Keys.D))
                {
                    frog.HeadTurnRate = -1;
                }
                else
                {
                    frog.HeadTurnRate = 0;
                }

                // Get the frog to lift his head
                if (keyboardState.IsKeyDown(Keys.W))
                {
                    frog.HeadLiftRate = 1;
                }
                else if (keyboardState.IsKeyDown(Keys.S))
                {
                    frog.HeadLiftRate = -1;
                }
                else
                {
                    frog.HeadLiftRate = 0;
                }

                if ((keyboardState.IsKeyDown(Keys.Escape)))
                {
                    graphics.ToggleFullScreen();
                }

                //lasers
                if ((keyboardState.IsKeyDown(Keys.F)))
                {
                    frog.FireLaser();
                }

                lastKeyboardState = keyboardState;

                camera.Center = frog.Position;
                camera.DesiredEye = Vector3.Transform(new Vector3(0, 318, -3000), frog.Transform);

                foreach (LaserFire.LaserBlast blast in frog.LaserFire.LaserBlasts)
                {
                    batField.TestLaserForCollision(blast.position);
                }

                // TODO: Add your update logic here
                frog.Update(gameTime);
                batField.Update(gameTime);
                // Update audioEngine
                audioEngine.Update();
            }
            else if (EndScreen)
            {
                if ((keyboardState.IsKeyDown(Keys.Q)))
                {
                    Exit();
                }
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            if (SplashScreen)
            {
                GraphicsDevice.Clear(Color.Green);
                spriteBatch.Begin();
                Rectangle screenRectangle = new Rectangle(0, 0, 1200, 800);
                spriteBatch.Draw(backgroundTexture, screenRectangle, Color.White);
                spriteBatch.DrawString(splashfont, "Welcome to the Frog Game \n Press P to continue", new Vector2(500, 400), Color.White);
                spriteBatch.End();
                GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            }
            else if (!SplashScreen && !EndScreen)
            {
                GraphicsDevice.DepthStencilState = DepthStencilState.Default;
                GraphicsDevice.Clear(Color.White);


                batField.Draw(graphics, gameTime);
                terrain.Draw(graphics, gameTime);
                frog.Draw(graphics, gameTime);

                string scoreString = String.Format("{0:d}", score);
                spriteBatch.Begin();
                spriteBatch.DrawString(splashfont, scoreString, new Vector2(10, 10), Color.White);
                spriteBatch.End();
            }
            else if (EndScreen)
            {
                GraphicsDevice.Clear(Color.Red);
                spriteBatch.Begin();
                Rectangle screenRectangle = new Rectangle(0, 0, 1200, 800);
                spriteBatch.Draw(backgroundTexture, screenRectangle, Color.White);
                spriteBatch.DrawString(splashfont, "Great Job Killing Bats! \n Press Q to quit", new Vector2(500, 400), Color.White);
                spriteBatch.End();
                GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            }
            base.Draw(gameTime);
        }

        private void DrawModel(Model model, Matrix world)
        {
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index] * world;
                    effect.View = this.Camera.View;
                    effect.Projection = this.Camera.Projection;
                }
                mesh.Draw();
            }
        }
    }
}
